<template>
  <a-card :title="title" :loading="loading" :bordered="false">
    <span slot="extra">
      <a @click="queryCardInfo" style="margin-right: 16px">
        <a-icon type="redo"/>
        刷新
      </a>
      <a v-if="card !== null && card.cardState === 0" @click="handleLose">挂失</a>
      <a v-else @click="handleApply">申请租借卡</a>
    </span>
    <a-descriptions v-if="card === null">
      <a-descriptions-item>未申请租借卡</a-descriptions-item>
    </a-descriptions>
    <a-descriptions v-else-if="card.cardState === 0">
      <a-descriptions-item label="余额">{{ card.balance }} 元</a-descriptions-item>
      <a-descriptions-item label="总骑行时间">{{ card.during }} 分钟</a-descriptions-item>
      <a-descriptions-item label="总骑行距离">{{ card.distance }} 公里</a-descriptions-item>
    </a-descriptions>
    <a-descriptions v-else :column="3">
      <a-descriptions-item label="您挂失的租借卡中还存有如下信息" :span="3"></a-descriptions-item>
      <a-descriptions-item label="余额">{{ card.balance }} 元</a-descriptions-item>
      <a-descriptions-item label="总骑行时间">{{ card.during }} 分钟</a-descriptions-item>
      <a-descriptions-item label="总骑行距离">{{ card.distance }} 公里</a-descriptions-item>
    </a-descriptions>
    <add-card ref="addCard" @ok="handleOk"></add-card>
    <lose-card ref="loseCard" @ok="handleOk"></lose-card>
  </a-card>
</template>

<script>
import {queryCard} from '@/api/bike/card'
import AddCard from './AddCard'
import LoseCard from './LoseCard'

export default {
  name: 'CardView',
  components: {
    AddCard,
    LoseCard,
  },
  data () {
    return {
      loading: true,
      card: null,
      title: '',
    }
  },
  created () {
    this.queryCardInfo()
  },
  methods: {
    handleApply () {
      this.$refs.addCard.add(this.card)
    },
    handleLose () {
      this.$refs.loseCard.lose(this.card)
    },
    updateTitle (card) {
      this.title = '租借卡号：' + (card === null || card.cardState === 1 ? '无' : card.cardNumber)
    },
    queryCardInfo () {
      this.title = '租借卡号：无'
      this.card = null
      this.loading = true
      queryCard().then(res => {
        if (res.message === 'success') {
          this.card = res.result
          this.updateTitle(this.card)
        } else {
          this.$message.error(res.result || '查询租借卡信息失败')
        }
        this.loading = false
      }).catch(err => {
        console.log(err)
        this.$message.error('查询租借卡信息失败')
        this.loading = false
      })
    },
    handleOk () {
      this.queryCardInfo()
    }
  }
}
</script>

<style scoped>

</style>
